<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>12 发布订阅1</title>
</head>

<body>
  <script>
    (function () {
      class Sub {
        pond = [];
        on(func) {
          let pond = this.pond;
          !pond.includes(func) ? pond.push(func) : null;
        }
        off(func) {
          this.pond = this.pond.filter(item => item !== func);
        }
        emit(...params) {
          this.pond.forEach(item => item(...params));
        }
      }
      window.subscribe = () => {
        return new Sub();
      }
    })();

    let fn1 = (x, y) => console.log('fn1', x, y);
    let fn2 = () => {
      console.log('fn2')
      sub1.off(fn1);
      sub1.off(fn2);
    };
    let fn3 = () => console.log('fn3');
    let fn4 = () => console.log('fn4');
    let fn5 = (x, y) => console.log('fn5', x, y);

    let sub1 = subscribe();
    let sub2 = subscribe();

    sub1.on(fn1);
    sub1.on(fn2);
    sub1.on(fn3);
    sub1.on(fn4);
    sub1.on(fn5);
    // 测试订阅重复的
    sub2.on(fn1);
    sub2.on(fn3);

    document.body.onclick = function () {
      sub1.emit(10, 20);
    }

    setTimeout(() => {
      sub2.emit(10, 20);
    }, 1000)
  </script>
</body>

</html>